package com.ganmiao.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁
 */
@Slf4j
@Service
public class RedisLockUtils {

    @Autowired
    ApplicationContext applicationContext;

    private RedissonClient redissonClient;

    @Autowired
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 加锁：不设置过期时间，自动续期
     *
     * @param rLock
     * @param waitTime 等待时间，单位：秒
     */
    public boolean lockByRenew(RLock rLock, long waitTime) throws InterruptedException {
        if (rLock.tryLock(waitTime, TimeUnit.SECONDS)) {
            log.info(String.format("lock [%s] success！", rLock.getName()));
            return true;
        } else {
            log.warn(String.format("lock [%s] failed！", rLock.getName()));
            return false;
        }
    }

    /**
     * 加锁：设置加锁时间，不会自动续期
     *
     * @param rLock
     * @param waitTime  等待时间，单位：秒
     * @param leaseTime 加锁时间，单位：秒
     */
    public boolean lock(RLock rLock, long waitTime, long leaseTime) throws InterruptedException {
        if (rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS)) {
            log.info(String.format("lock [%s] success！", rLock.getName()));
            return true;
        } else {
            log.info(String.format("lock [%s] failed！", rLock.getName()));
            return false;
        }
    }

    /**
     * 释放锁
     *
     * @param rLock
     */
    public void releaseLock(RLock rLock) {
        if (rLock == null) {
            return;
        }
        if (rLock.isHeldByCurrentThread()) {
            rLock.unlock();
            log.info(String.format("thread[%s] release lock[%s]success！！！", Thread.currentThread().getName(), ((RLock) rLock).getName()));
        }
    }

    public RLock getLocked(String lockKey) {
        return redissonClient.getLock(lockKey);
    }

    public boolean isLocked(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.isLocked();
    }
}
